<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
/**
 * This is the model class for table "xa_type".
 *
 * @property integer $id
 * @property integer $xa_parent_id
 * @property string $xa_name
 * @property string $xa_url
 * @property string $xa_state
 * @property string $xa_create_time
 * @property string $xa_update_time
 * @property string $xa_remark
 */
class Type extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'xa_type';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['xa_parent_id'], 'integer'],
            [['xa_name', 'xa_url','xa_state', 'xa_create_time', 'xa_update_time', 'xa_remark'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'xa_parent_id' => '上级栏目',
            'xa_name' => '栏目名称',
            'xa_url' => '栏目链接',
            'xa_state' => '栏目状态',
            'xa_create_time' => '创建时间',
            'xa_update_time' => '修改时间',
            'xa_remark' => '备注',
        ];
    }

    /**
     * 获取所有的分类
     */
    public function getCategories()
    {
        $data = self::find()->all();
        $data = ArrayHelper::toArray($data);
        //var_dump($data);die;
        return $data;
    }

    /**
     *遍历出各个子类 获得树状结构的数组
     */
    public static function getTree($data,$xa_parent_id = 0,$lev = 1)
    {
        $tree = [];
        foreach($data as $value){
            if($value['xa_parent_id'] == $xa_parent_id){
                $value['xa_name'] = str_repeat('|--',$lev).$value['xa_name'];
                $tree[] = $value;
                $tree = array_merge($tree,self::getTree($data,$value['id'],$lev+1));
            }
        }
        return $tree;
    }

    /**
     * 得到相应  id  对应的  分类名  数组
     */
    public function getOptions()
    {
        $data = $this->getCategories();
        $tree = $this->getTree($data);
        $list = ['添加顶级分类'];
        foreach($tree as $value){
            $list[$value['id']] = $value['xa_name'];
        }
        //var_dump($list);die;
        return $list;
    }

    /**
     * 保存
     */
    public function Conserve()
     {
         if(!$this->validate())
         {
             return false;
         }
         $this->xa_create_time=date('Y-m-d H:i:s');
         if($this->save())
         {
             return true;
         }
     }




}
